package top.ywlog.permission.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.request.AclParam;
import top.ywlog.permission.dao.SysAclMapper;
import top.ywlog.permission.exception.ParamException;
import top.ywlog.permission.model.SysAcl;
import top.ywlog.permission.util.IpUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author: Durian
 * @date: 2020/10/24 18:24
 * @description:
 */
@Slf4j
@Service
public class SysAclService
{
    private static DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @Resource
    private SysAclMapper sysAclMapper;

    @Transactional
    public void saveAcl(AclParam aclParam)
    {
        if (checkExist(aclParam.getAclModuleId(), aclParam.getName(), aclParam.getId()))
        {
            throw new ParamException("当前权限模块下面存在相同名称的权限点");
        }
        SysAcl acl = SysAcl.builder().name(aclParam.getName()).aclModuleId(aclParam.getAclModuleId()).url(aclParam.getUrl())
                .type(aclParam.getType()).status(aclParam.getStatus()).seq(aclParam.getSeq()).remark(aclParam.getRemark()).build();
        acl.setCode(generateCode());
        acl.setOperator(RequestHolder.getCurrentUser().getUsername());
        acl.setOperateTime(LocalDateTime.now());
        acl.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysAclMapper.insertSelective(acl);
    }

    @Transactional
    public void update(AclParam aclParam)
    {
        if (checkExist(aclParam.getAclModuleId(), aclParam.getName(), aclParam.getId()))
        {
            throw new ParamException("当前权限模块下面存在相同名称的权限点");
        }
        SysAcl before = sysAclMapper.selectByPrimaryKey(aclParam.getId());
        if (before == null)
        {
            throw new ParamException("待更新的权限点不存在");
        }

        SysAcl after = SysAcl.builder().id(aclParam.getId()).name(aclParam.getName()).aclModuleId(aclParam.getAclModuleId()).url(aclParam.getUrl())
                .type(aclParam.getType()).status(aclParam.getStatus()).seq(aclParam.getSeq()).remark(aclParam.getRemark()).build();
        after.setCode(generateCode());
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateTime(LocalDateTime.now());
        after.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));

        sysAclMapper.updateByPrimaryKeySelective(after);
    }

    private boolean checkExist(int aclModuleId, String name, Integer id)
    {
        return sysAclMapper.countByNameAndAclModuleId(aclModuleId, name, id) > 0;
    }

    private String generateCode()
    {
        return dateFormat.format(LocalDateTime.now()) + "_" + (int) (Math.random() * 100);
    }
}
